/**
 * 
 */
package kit4j.ui.cs.swing.dnd;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 对序列化对象数据进行传输操作的数据提供者类型。
 * 
 * @author MiniKnife
 * 
 */
public class SerializedObjectTransferable implements Transferable {

	/**
	 * 要进行传输操作的序列化对象。
	 */
	private Serializable object;

	/**
	 * 
	 */
	private List<DataFlavor> flavorList;

	public SerializedObjectTransferable(Serializable object) {
		this.object = object;
		flavorList = createDataFlavorWithObject(object);
	}

	private List<DataFlavor> createDataFlavorWithObject(Object object) {
		List<DataFlavor> flavorList = new ArrayList<DataFlavor>();
		flavorList.add(DataFlavor.stringFlavor);

		Class<?> type = object.getClass();
		while (type != null) {
			flavorList.add(new DataFlavor(type, null));

			type = type.getSuperclass();
		}

		return flavorList;
	}

	/**
	 * @see java.awt.datatransfer.Transferable#getTransferData(java.awt.datatransfer.DataFlavor)
	 */
	@Override
	public Object getTransferData(DataFlavor flavor)
			throws UnsupportedFlavorException, IOException {
		if (!isDataFlavorSupported(flavor)) {
			throw new UnsupportedFlavorException(flavor);
		}

		if (DataFlavor.stringFlavor.equals(flavor)) {
			return object.toString();
		}

		return object;
	}

	/**
	 * @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
	 */
	@Override
	public DataFlavor[] getTransferDataFlavors() {
		return flavorList.toArray(new DataFlavor[0]);
	}

	/**
	 * @see java.awt.datatransfer.Transferable#isDataFlavorSupported(java.awt.datatransfer.DataFlavor)
	 */
	@Override
	public boolean isDataFlavorSupported(DataFlavor flavor) {
		return flavorList.contains(flavor);
	}

}
